package com.my.commonlibrary.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.my.commonlibrary.CommonApplication;
import com.my.commonlibrary.R;
import com.my.commonlibrary.base.BaseFragment;
import com.my.commonlibrary.utils.ToastUtil;
import com.my.commonlibrary.widget.DialogFactory;
import com.tamic.novate.PersistentCookieStore;

import org.apache.http.client.HttpClient;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Cookie;

/**
 * Author : Cooper
 * Time : 2016/9/28  09:35
 * Description : WebView 与 H5 的实现
 * WebView 详细介绍  http://blog.csdn.net/u012500046/article/details/50592174
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class H_WebViewFragment extends BaseFragment implements View.OnKeyListener{

    private final String APP_CACAHE_DIRNAME = "webview_cache";
    @Bind(R.id.mWebView)
    WebView mWebView;
    @Bind(R.id.mProgressBar)
    ProgressBar mProgressBar;
    @Bind(R.id.mWebIcon_iv)
    ImageView mWebIconIv;
    @Bind(R.id.mWebText_tv)
    TextView mWebTextTv;

    private ProgressDialog mProgressDialog;
    private Dialog mLoadingDialog;

    //    private final String URL = "https://www.wanglibao.com/app/about";
//      private final String URL = "http://www.52jiaoshi.com/index.php/Home/Live/detail?id=6645&from=android";
//    private final String URL = "file:///android_asset/test.html ";
//    private final String URL = "http://www.baidu.com";
//    private final String URL = "https://php1.wanglibao.com/pro/wap/product_info/p2p_info.html?id=100001601";
//    private final String URL = "http://stat.wanglibao.com:10000/applog/push.php";
//    private final String URL = "https://test.wanglibao.com/wechat/index.html#1";
//    private final String URL = "http://www.huangjinhezi.com/wechat/safetyGuarantee.html";
    private final String URL = "https://test.izhuanbei.com/wechat/notice/notice.html";
//    private final String URL = "https://test.wanglibao.com/wechat/share/index.html";

    //打开本包内asset目录下的index.html文件
    //wView.loadUrl("file:///android_asset/index.html");

    //打开本地sd卡内的index.html文件
    //wView.loadUrl("content://com.android.htmlfileprovider/sdcard/index.html");

    @Override
    protected int getFragmentLayoutRes() {
        return R.layout.frag_home_webview_layout;
    }

    @Override
    protected void initFragmentData() {
        mProgressDialog = DialogFactory.createProgressDialog(getActivity());
        mLoadingDialog = DialogFactory.showNewLoading(getActivity());
//        syncCookie(getActivity(),URL);
        mWebView.loadUrl(URL);
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setWebChromeClient(new MyWebChromeClient());
//        // 执行网页中的js程序
        mWebView.getSettings().setJavaScriptEnabled(true);
//        mWebView.setOnKeyListener(this);

        // JS调用android中的方法
        // var obj = window.WangLiBao.JsCallAndroid("https://"+host+path); 注意WangLiBao这个属性一定要一致。
        // 这个方法可以定义任意参数，任意名字
//        mWebView.addJavascriptInterface(new DemoJavaScriptInterface(),"WangLiBao");
        // 解决在webview里面加载https url的时候，如果里面需要加载http的资源或者重定向的时候，
        // webview会block页面加载。这应该是Android 4.4以来google对安全机制的提升。
        // 图片加载不出来，显示"the image could not be loaded"
//        mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//        initWebViewSettings();
//        initUserAgent();
//        initWebViewCache();
//        initWebViewOtherSeting();
    }

    /**
     * init WebView Settings
     * */
    private void initWebViewSettings(){
        //        myWebView.getSettings().setSupportZoom(true);
        //        myWebView.getSettings().setBuiltInZoomControls(true);
        //        myWebView.getSettings().setDefaultFontSize(12);
        //        myWebView.getSettings().setLoadWithOverviewMode(true);
        // 设置可以访问文件
        mWebView.getSettings().setAllowFileAccess(true);
        //如果访问的页面中有Javascript，则webview必须设置支持Javascript
        mWebView.getSettings().setJavaScriptEnabled(true);
//        mWebView.getSettings().setUserAgentString(MyApplication.getUserAgent());
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setDatabaseEnabled(true);
    }

    /**
     * Sync Cookie
     */
    private void syncCookie(Context context, String url){
        try{
            Log.d("Nat: webView.syncCookie.url", url);

            CookieSyncManager.createInstance(context);

            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();// 移除
            cookieManager.removeAllCookie();
            String oldCookie = cookieManager.getCookie(url);
            if(oldCookie != null){
                Log.d("Nat: webView.syncCookieOutter.oldCookie", oldCookie);
            }
//            PersistentCookieStore persistentCookieStore = getActivity().getApplication().getCookieStore();
//            for (Cookie cookie : persistentCookieStore.getCookies()) {
//
//                String cookieString = cookie.getName() + "=" + cookie.getValue()
//                        + "; domain=" + cookie.getDomain()
//                        + "; path=" + cookie.getPath();
//                cookieManager.setCookie(url, cookieString);
//                CookieSyncManager.getInstance().sync();
//            }
            String cookieString = "name" + "=" + "jack"
                    + "; domain=" + "age"
                    + "; path=" + "home";
            cookieManager.setCookie(url, cookieString);
            CookieSyncManager.getInstance().sync();
            String newCookie = cookieManager.getCookie(url);
            if(newCookie != null){
                Log.d("Nat: webView.syncCookie.newCookie", newCookie);
            }
        }catch(Exception e){
            Log.e("Nat: webView.syncCookie failed", e.toString());
        }
    }

    /**
     * 获取和设置UserAgent
     */
    private void initUserAgent() {
        //Mozilla/5.0 (Linux; Android 5.0; vivo X5Pro D Build/LRX21M)
        //AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile Safari/537.36
        String agent = mWebView.getSettings().getUserAgentString();
        Log.e("H_WebViewFragment","agent == "+agent);
        mWebView.getSettings().setUserAgentString(agent+"/wlb");
    }

    /**
     * JS调用android中的方法，需创建一个JavaScriptInterface，
     * 实现JsCallAndroid方法
     */
    class DemoJavaScriptInterface {
        DemoJavaScriptInterface() {
        }
        @JavascriptInterface
        public void JsCallAndroid(String url) {
            ToastUtil.showToast(url);
        }
    }

    /**
     * 初始化webview缓存配置
     */
    private void initWebViewCache() {
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // 设置缓存模式
        // 开启 DOM storage API 功能
        mWebView.getSettings().setDomStorageEnabled(true);
        // 开启 database storage API 功能
        mWebView.getSettings().setDatabaseEnabled(true);
        String cacheDirPath = mActivity.getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
        // String cacheDirPath =
        // getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;
        // 设置数据库缓存路径
        mWebView.getSettings().setDatabasePath(cacheDirPath);
        // 设置 Application Caches 缓存目录
        mWebView.getSettings().setAppCachePath(cacheDirPath);
        // 开启 Application Caches 功能
        mWebView.getSettings().setAppCacheEnabled(true);

        // 清除缓存
//        mWebView.clearCache(true);
    }

    private void initWebViewOtherSeting() {
        //支持js
        mWebView.getSettings().setJavaScriptEnabled(true);

        //将图片调整到适合webview的大小
        mWebView.getSettings().setUseWideViewPort(false);
        mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        //支持缩放变焦
        mWebView.getSettings().setSupportZoom(true);

        //设置是否支持缩放
        mWebView.getSettings().setBuiltInZoomControls(false);

        //支持内容重新布局
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        //多窗口
        mWebView.getSettings().supportMultipleWindows();

        //优先使用webview中缓存
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

        //关闭webview中缓存
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

        //设置可以访问文件
        mWebView.getSettings().setAllowFileAccess(true);

        //当webview调用requestFocus时为webview设置节点
        mWebView.getSettings().setNeedInitialFocus(true);

        //设置支持缩放
        mWebView.getSettings().setBuiltInZoomControls(true);

        //支持通过JS打开新窗口
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

        // 缩放至屏幕的大小
        mWebView.getSettings().setLoadWithOverviewMode(true);

        //支持自动加载图片
        mWebView.getSettings().setLoadsImagesAutomatically(true);

        //是否显示网络图像
        mWebView.getSettings().setBlockNetworkImage(true);

        //设置默认的字体大小
//        mWebView.getSettings().setDefaultFontSize(int size);

        //设置默认文字编码
//        mWebView.getSettings().setDefaultTextEncodingName(String encoding);

        //设置固定使用的字体
//        mWebView.getSettings().setFixedFontFamily(String font);

        //设置用鼠标激活被选项
//        mWebView.getSettings().setLightTouchEnabled(boolean enable);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    // 点击返回键，网页后退
    @Override
    public boolean onKey(View view, int code, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && code == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0) {
            if (mWebView != null && mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                mActivity.finish();
            }
            return true;
        }
        return false;
    }

    class MyWebViewClient extends WebViewClient {

        // 在点击请求的是链接是才会调用，重写此方法返回true表明点击
        // 网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边。
        // 解决加载网页时，跳转到系统浏览器问题
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            mLoadingDialog.show();
            return false;
        }

        // 进度条 开启
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
//            mProgressBar.setVisibility(View.VISIBLE);
        }

        // 进度条 结束
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
//            mProgressBar.setVisibility(View.GONE);
            mLoadingDialog.dismiss();
        }

        // 在加载页面资源时会调用，每一个资源（比如图片）的加载都会调用一次。
        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        // 在onReceiveError我们可以自定义网页的错误页面。
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        // 重写此方法可以让webview处理https请求。
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            super.onReceivedSslError(view, handler, error);
            handler.proceed();
        }

        // 重写此方法才能够处理在浏览器中的按键事件。
        @Override
        public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
            return super.shouldOverrideKeyEvent(view, event);
        }
    }

    class MyWebChromeClient extends WebChromeClient {

        // 当前网页加载的进度
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (newProgress == 100) {
//                mProgressDialog.dismiss();
            } else {
//                mProgressDialog.setProgress(newProgress);
            }
        }

        /**
         * 打印web的log信息
         * @param consoleMessage
         * @return
         */
        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            Log.e("ah == console", "["+consoleMessage.messageLevel()+"] "+ consoleMessage.message() + "(" +consoleMessage.sourceId()  + ":" + consoleMessage.lineNumber()+")");
            return super.onConsoleMessage(consoleMessage);
        }

        // 当前页面title
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            mWebTextTv.setText(title);
        }

        // 当前页面icon
        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            super.onReceivedIcon(view, icon);
            mWebIconIv.setImageBitmap(icon);
        }

        // 支持H5网站视频全屏回调 开启全屏
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            super.onShowCustomView(view, callback);
        }

        // 支持H5网站视频全屏回调 取消全屏
        @Override
        public void onHideCustomView() {
            super.onHideCustomView();
        }

        @Override
        public void onRequestFocus(WebView view) {
            super.onRequestFocus(view);
        }

        // 用新的webview打开新网页
        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
        }

        // 关闭
        @Override
        public void onCloseWindow(WebView window) {
            super.onCloseWindow(window);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
            b.setTitle("Alert");
            b.setMessage(message);
            b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm();
                }
            });
            b.setCancelable(false);
            b.create().show();
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
            b.setTitle("Confirm");
            b.setMessage(message);
            b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm();
                }
            });
            b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    result.cancel();
                }
            });
            b.create().show();
            return true;
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
//            final View v = View.inflate(TestAlertActivity.this, R.layout.prompt_dialog, null);
//            ((TextView) v.findViewById(R.id.prompt_message_text)).setText(message);
//            ((EditText) v.findViewById(R.id.prompt_input_field)).setText(defaultValue);
            TextView textView = new TextView(getActivity());
            textView.setText(message);
            EditText editText = new EditText(getActivity());
            LinearLayout linearLayout = new LinearLayout(getActivity());
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            linearLayout.addView(textView);
            linearLayout.addView(editText);
            AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
            b.setTitle("Prompt");
            b.setView(linearLayout);
            b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
//                    String value = ((EditText) v.findViewById(R.id.prompt_input_field)).getText().toString();
//                    result.confirm(value);
                    result.confirm();
                }
            });
            b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    result.cancel();
                }
            });
            b.create().show();
            return true;
        }

    }
}
